package com.sl.core.engine.datasource;

import lombok.extern.slf4j.Slf4j;
import org.anyline.adapter.EnvironmentWorker;
import org.anyline.data.adapter.DriverAdapter;
import org.anyline.data.datasource.ApplicationConnectionHolder;
import org.anyline.data.datasource.ThreadConnectionHolder;
import org.anyline.data.jdbc.adapter.init.DefaultJDBCActuator;
import org.anyline.data.runtime.DataRuntime;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

@Slf4j
public class ProcessJDBCActuator extends DefaultJDBCActuator {

    public static void reg(EnvironmentWorker start) {
        start.regBean("anyline.environment.data.driver.actuator.jdbc", new ProcessJDBCActuator());
    }

    public Connection getConnection(DriverAdapter adapter, DataRuntime runtime, DataSource datasource) {
        Connection con = null;
        try{
            //当前线程中已经开启了事务的 用事务连接
            con = ProcessConnectionHolder.get(runtime.getKey());
            if(null == con) {
                con = datasource.getConnection();
            }
        }catch (Exception e) {
            log.error("连接 异常:", e);
        }
        return con;
    }

    @Override
    public void releaseConnection(DriverAdapter adapter, DataRuntime runtime, Connection connection, DataSource datasource) {
        try {
            if(ThreadConnectionHolder.contains(datasource, connection)
                    || ApplicationConnectionHolder.contains(datasource, connection)
                    || ProcessConnectionHolder.contains(runtime.getKey())) {
                //有事务不要关闭，在事务管理器中关闭
                return;
            }
            connection.close();
        } catch (SQLException e) {
            log.error("释放连接 异常:", e);
        }
    }
}
